package com.closer.service.biz.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.closer.service.biz.user.dto.*;
import com.closer.service.biz.user.dto.vo.LoginUserVO;
import com.closer.service.biz.user.dto.vo.UserVO;
import com.closer.service.biz.user.enums.UserRoleEnum;
import com.closer.service.biz.user.validator.UserValidator;
import com.closer.service.support.exception.BusinessException;
import com.closer.service.support.exception.ErrorCode;
import com.closer.service.support.exception.ThrowUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.closer.service.biz.user.entity.User;
import com.closer.service.repository.UserMapper;
import com.closer.service.biz.user.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 服务层实现。
 *
 * @author closer
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService{

    private final UserValidator validator;

    private static final String SALT = "closer";

    public UserServiceImpl(UserValidator validator) {
        this.validator = validator;
    }

    @Override
    public long userRegister(UserRegisterRequest params) {
        ThrowUtils.throwIf(params==null, ErrorCode.PARAMS_ERROR);
        var userAccount = params.getUserAccount();
        var userPassword = params.getUserPassword();
        var checkPassword = params.getCheckPassword();
        //1.校验
        validator.validateRegister(userAccount, userPassword, checkPassword);

        // 2. 加密
        var encryptPassword = getEncryptPassword(userPassword);
        // 3. 插入数据
        var user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(UserRoleEnum.USER.getValue());
        var saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        return user.getId();
    }

    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        var loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public LoginUserVO userLogin(UserLoginRequest params) {
        ThrowUtils.throwIf(params == null, ErrorCode.PARAMS_ERROR);
        var userAccount = params.getUserAccount();
        var userPassword = params.getUserPassword();
        // 1. 校验
        validator.validateLogin(userAccount, userPassword);
        // 2. 加密
        var encryptPassword = getEncryptPassword(userPassword);
        // 查询用户是否存在
        var queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        var user = this.mapper.selectOneByQuery(queryWrapper);
        // 用户不存在
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        return this.getLoginUserVO(user);
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        var userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public long add(UserAddRequest params) {
        ThrowUtils.throwIf(params == null, ErrorCode.PARAMS_ERROR);
        var user = new User();
        BeanUtil.copyProperties(params, user);
        // 默认密码 12345678
        final String DEFAULT_PASSWORD = "12345678";
        var encryptPassword = getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        var result = this.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return user.getId();
    }

    @Override
    public boolean updateUser(UserUpdateRequest params) {
        if (params == null || params.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        var user = new User();
        BeanUtil.copyProperties(params, user);
        var result = this.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return true;
    }

    @Override
    public Page<UserVO> listUserVOByPage(UserQueryRequest params) {
        ThrowUtils.throwIf(params == null, ErrorCode.PARAMS_ERROR);
        var pageNum = params.getPageNum();
        var pageSize = params.getPageSize();
        var userPage = this.page(Page.of(pageNum, pageSize),
                this.getQueryWrapper(params));
        // 数据脱敏
        Page<UserVO> userVOPage = new Page<>(pageNum, pageSize, userPage.getTotalRow());
        var userVOList = this.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return userVOPage;
    }

    @Override
    public QueryWrapper getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        var id = userQueryRequest.getId();
        var userAccount = userQueryRequest.getUserAccount();
        var userName = userQueryRequest.getUserName();
        var userProfile = userQueryRequest.getUserProfile();
        var userRole = userQueryRequest.getUserRole();
        var sortField = userQueryRequest.getSortField();
        var sortOrder = userQueryRequest.getSortOrder();
        return QueryWrapper.create()
                .eq("id", id)
                .eq("userRole", userRole)
                .like("userAccount", userAccount)
                .like("userName", userName)
                .like("userProfile", userProfile)
                .orderBy(sortField, "ascend".equals(sortOrder));
    }

}
